﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace Hangout.Client.Accounts
{
    public partial class ViewProfile : PhoneApplicationPage
    {

        

        private int UserID;

        private MeetupService.Meetup CurrentHangout;

        public ViewProfile()
        {
            InitializeComponent();
        }

        private int GetID()
        {
            try
            {
                int a = -1;
                int.TryParse(NavigationContext.QueryString["id"], out a);
                return a;
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
                return -1;
            }
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                int id = GetID();
                UserID = id;
                if (id == -1)
                {
                    NavigateToDashboard();
                    return;
                }
                if (NavigationContext.QueryString.Where(o => o.Key == "TrophyDisplay").Count() > 0)
                {
                    if (NavigationContext.QueryString["TrophyDisplay"] == "true")
                    {
                        ChangeToTrophyDisplay();
                    }
                }


                TrophyList.TrophyLoadCompleted += new Controls.Trophy.TrophyList.LoadComplated(TrophyList_TrophyLoadCompleted);
                GetUserProfile(id);
                LoadHangouts(id);
                LoadTrophy(id);
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }

        }

        private void ChangeToTrophyDisplay()
        {
            MainPivot.SelectedIndex = 1;
        }

        void TrophyList_TrophyLoadCompleted(TrophyService.GetUserTrophiesCompletedEventArgs e)
        {
            try
            {
                TrophyPG.Visibility = System.Windows.Visibility.Collapsed;
                ShowTrophy.Begin();
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }

        }

        private void LoadTrophy(int id)
        {
            try
            {
                TrophyList.UserID = id;
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        private void LoadHangouts(int id)
        {
            try
            {
                HangoutList.ShowMoreButton = true;
                HangoutList.ShoutNewHangoutSelected += new EventHandler(HangoutList_ShoutNewHangoutSelected);
                HangoutList.HangoutSelected += new Controls.Hangouts.HangoutList.HangoutSelectedHelper(HangoutList_HangoutSelected);
                HangoutList.ProfileNameSeletcted += new Controls.Hangouts.HangoutList.ProfileNameSelectedHelper(HangoutList_ProfileNameSeletcted);
                HangoutList.ProfilePicSeletcted += new Controls.Hangouts.HangoutList.ProfilePicSelectedHelper(HangoutList_ProfilePicSeletcted);
                HangoutList.StatusTextSeletcted += new Controls.Hangouts.HangoutList.StatusTextSelectedHelper(HangoutList_StatusTextSeletcted);
                HangoutList.PinSeletcted += new Controls.Hangouts.HangoutList.PinSelectedHelper(HangoutList_PinSeletcted);
                HangoutList.UnpinSeletcted += new Controls.Hangouts.HangoutList.UnPinSelectedHelper(HangoutList_UnpinSeletcted);
                HangoutList.ListSV.Height = 470;
                HangoutList.MoreHangoutClicked += new Controls.Hangouts.HangoutList.MoreHangoutClickedHelper(HangoutList_MoreHangoutClicked);
                
                Services.MeetupServiceClient.GetUserHangoutCompleted += new EventHandler<MeetupService.GetUserHangoutCompletedEventArgs>(client_GetUserHangoutCompleted);
                Services.MeetupServiceClient.GetUserHangoutAsync(id, HangoutList.Take, HangoutList.Skip, Settings.Settings.FacebookAccessToken);
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        private void DetachEvents()
        {
            try
            {
                HangoutList.ShoutNewHangoutSelected -= HangoutList_ShoutNewHangoutSelected;
                HangoutList.StatusTextSeletcted -= HangoutList_StatusTextSeletcted;
                HangoutList.HangoutSelected -= HangoutList_HangoutSelected;
                HangoutList.ProfileNameSeletcted -= HangoutList_ProfileNameSeletcted;
                HangoutList.ProfilePicSeletcted -= HangoutList_ProfilePicSeletcted;
                HangoutList.PinSeletcted -= HangoutList_PinSeletcted;
                HangoutList.UnpinSeletcted -= HangoutList_UnpinSeletcted;
                HangoutList.MoreHangoutClicked -= HangoutList_MoreHangoutClicked;
            }
            catch (System.Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void HangoutList_ShoutNewHangoutSelected(object sender, EventArgs e)
        {
            try
            {
                Dispatcher.BeginInvoke(() =>
                    {
                        NavigationService.Navigate(new Uri(Navigation.InitiateHangout, UriKind.RelativeOrAbsolute));
                    });
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void HangoutList_StatusTextSeletcted(MeetupService.Meetup data)
        {
            try
            {
                if (data.HangoutID != null)
                {
                    NavigateToHangoutPage(data.HangoutID);
                }
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        private void NavigateToHangoutPage(int id)
        {
            try
            {
                Dispatcher.BeginInvoke(() =>
                    {
                        NavigationService.Navigate(new Uri(Navigation.Hangout + "?id=" + id, UriKind.RelativeOrAbsolute));
                    });
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void HangoutList_MoreHangoutClicked(int take, int skip)
        {
            try
            {
                HangoutList.ShowMorePG = true;
                
                Services.MeetupServiceClient.GetUserHangoutCompleted+=new EventHandler<MeetupService.GetUserHangoutCompletedEventArgs>(client_GetUserHangoutCompleted);
                Services.MeetupServiceClient.GetUserHangoutAsync(Settings.Settings.UserID, HangoutList.Take, HangoutList.Skip, Settings.Settings.FacebookAccessToken);
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void HangoutList_UnpinSeletcted(MeetupService.Meetup data)
        {
            try
            {
                
                Services.MeetupServiceClient.UnPinHangoutCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_UnPinHangoutCompleted);
                CurrentHangout = data;
                Services.MeetupServiceClient.UnPinHangoutAsync(UserID, data.HangoutID, Settings.Settings.FacebookAccessToken);
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void client_UnPinHangoutCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            Services.MeetupServiceClient.UnPinHangoutCompleted -= new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_UnPinHangoutCompleted);
            try
            {
                if (e.Error == null)
                {
                    HangoutList.DisplayPinImage(CurrentHangout);
                }
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void HangoutList_PinSeletcted(MeetupService.Meetup data)
        {
            try
            {
               
                Services.MeetupServiceClient.PinHangoutCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_PinHangoutCompleted);
                CurrentHangout = data;
                Services.MeetupServiceClient.PinHangoutAsync(UserID, data.HangoutID, Settings.Settings.FacebookAccessToken);
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void client_PinHangoutCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            Services.MeetupServiceClient.PinHangoutCompleted -= new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_PinHangoutCompleted);
            try
            {
                if (e.Error == null)
                {
                    HangoutList.DisplayUnPinImage(CurrentHangout);
                }

            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void HangoutList_ProfilePicSeletcted(MeetupService.Meetup data)
        {
            try
            {
                if (data.User.UserID != GetID())
                {
                    NavigateToViewProfile(data.User.UserID);
                }
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void HangoutList_ProfileNameSeletcted(MeetupService.Meetup data)
        {
            try
            {
                if (data.User.UserID != GetID())
                {
                    NavigateToViewProfile(data.User.UserID);
                }
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        private void NavigateToViewProfile(int id)
        {

            try
            {
                //navigate to hangout page
                Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri(Navigation.ViewProfile + "?id=" + id, UriKind.RelativeOrAbsolute));
                });

            }

            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void client_GetUserHangoutCompleted(object sender, MeetupService.GetUserHangoutCompletedEventArgs e)
        {
            Services.MeetupServiceClient.GetUserHangoutCompleted -= new EventHandler<MeetupService.GetUserHangoutCompletedEventArgs>(client_GetUserHangoutCompleted);

            try
            {
                HangoutList.ShowMorePG = false;
                HangoutPG.Visibility = System.Windows.Visibility.Collapsed;
                if (e.Error == null)
                {
                    if (e.Result.Count < HangoutList.Take)
                    {
                        HangoutList.ShowMoreButton = false;
                    }
                    HangoutList.Hangouts.AddRange(e.Result.ToList());
                    HangoutList.Hangouts = HangoutList.Hangouts.OrderByDescending(o => o.DateTimePosted).ToList();
                    HangoutList.RefreshList();
                    ShowHangouts.Begin();
                }
                else
                {
                    MessageBox.Show(ErrorText.Description, ErrorText.Caption, MessageBoxButton.OK);

                }

            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void HangoutList_HangoutSelected(MeetupService.Meetup e)
        {
            try
            {

                //navigate to hangout page
                Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri(Navigation.Hangout + "?id=" + e.HangoutID, UriKind.RelativeOrAbsolute));
                });

            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

       
        private void GetUserProfile(int id)
        {
            try
            {
                
                Services.AccountServiceClient.GetUserProfileCompleted += new EventHandler<AccountService.GetUserProfileCompletedEventArgs>(client_GetUserProfileCompleted);
                Services.AccountServiceClient.GetUserProfileAsync(id, Settings.Settings.FacebookAccessToken);
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void client_GetUserProfileCompleted(object sender, AccountService.GetUserProfileCompletedEventArgs e)
        {

            Services.AccountServiceClient.GetUserProfileCompleted -= new EventHandler<AccountService.GetUserProfileCompletedEventArgs>(client_GetUserProfileCompleted);
            try
            {
                if (e.Error == null)
                {
                    LoadUserInfo(e.Result);
                }
                else
                {
                    MessageBox.Show(ErrorText.Description, ErrorText.Caption, MessageBoxButton.OK);

                }
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        private void NavigateToDashboard()
        {
            try
            {
                Dispatcher.BeginInvoke(() =>
                {
                    if (NavigationService.CanGoBack)
                    {
                        var uri = NavigationService.BackStack.First().Source;

                        if (uri.ToString() == "/MainPage.xaml")
                        {
                            NavigationService.GoBack();
                        }
                        else
                        {
                            NavigationService.Navigate(new Uri(Navigation.Dashboard, UriKind.RelativeOrAbsolute));
                        }
                    }
                    else
                    {
                        NavigationService.Navigate(new Uri(Navigation.Dashboard, UriKind.RelativeOrAbsolute));
                    }

                });
            }
            catch (System.Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        private void LoadUserInfo(AccountService.UserProfile profile)
        {
            try
            {
                UserInfo.ScoreClicked += new EventHandler(UserInfo_ScoreClicked);
                UserInfo.StatusTextclicked += new EventHandler(UserInfo_StatusTextclicked);
                UserInfo.Profile = profile;
                UseDetailedInfo.Profile = profile;
                InfoPG.Visibility = System.Windows.Visibility.Collapsed;
                ShowInfo.Begin();
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void UserInfo_ScoreClicked(object sender, EventArgs e)
        {
            try
            {
                ChangeToTrophyDisplay();
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        void UserInfo_StatusTextclicked(object sender, EventArgs e)
        {
            try
            {
                Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri(Navigation.Hangout + "?id=" + UserInfo.Hangout.HangoutID, UriKind.RelativeOrAbsolute));
                });
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        private void dashboardBtn_Click(object sender, EventArgs e)
        {
            try
            {
                NavigateToDashboard();
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        #region NotificationControl

        public void AttachEvents()
        {
            try
            {
                NotificationControl.NavigateToHangout += new Controls.Notifications.NotificationReceived.IdHelper(NotificationControl_NavigateToHangout);
                NotificationControl.NavigateToProfile += new Controls.Notifications.NotificationReceived.IdHelper(NotificationControl_NavigateToProfile);
            }
            catch (System.Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);

            }
        }

        void NotificationControl_NavigateToProfile(int id)
        {
            try
            {
                NavigateToViewProfile(id);
            }
            catch (System.Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);

            }
        }

        void NotificationControl_NavigateToHangout(int id)
        {
            try
            {
                NavigateToHangout(id);
            }
            catch (System.Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);

            }
        }

        private void NavigateToHangout(int id)
        {
            try
            {
                //navigate to hangout page
                Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri(Navigation.Hangout + "?id=" + id, UriKind.RelativeOrAbsolute));
                });
            }
            catch (System.Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);

            }
        }

        

        #endregion

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            DetachEvents();
            base.OnNavigatedFrom(e);
        }

    }
}